import concurrent
import time
from concurrent.futures import ThreadPoolExecutor

import baseScript
from testcases.api_stress.mqtt_demo.utils import ContMysql


def bind_devices(username):
    """
    走绑定用户设备的流程
    :param username:
    :return:
    """

    cookie = baseScript.login(username, 'cc1234')
    # print(cookie)
    # 2获取mqtt配置信息
    # cookie = username
    # mqtt = baseScript.mqtt_conf(cookie)
    # print(mqtt, '\n','cookies = ', cookie)
    # 3.绑定设备
    baseScript.bind_set(cookie, username)
    # # # 4. 使用设备
    baseScript.use_set(cookie, username)
    # # # 5 查询设备信息
    # baseScript.check_device(cookie)
    # return cookie


def concurrent_login():
    tester_list = []
    with open('account/binduser.txt', mode='r', encoding='utf-8') as f:
        for _ in f:
            tester_list.append(_.strip())
    # print(li)
    tasks = set()
    with ThreadPoolExecutor(100) as t:
        for username in tester_list:
            # print(username, type(username))
            future = t.submit(baseScript.login, username.strip())
            tasks.add(future)
            if len(tasks) == 50:
                break
            # if tester_list.index(username) % 500 == 0 and tester_list.index(username) > 0:
            #     time.sleep(1)
                # pass
    try:
        count_fail = 0
        for future in concurrent.futures.as_completed(tasks):
            if future == None:
                count_fail += 1
            # print(future)
            err = future.exception()
            if err is not None:
                raise err
    except KeyboardInterrupt:
        print('stopped by hand')
    print(count_fail)


def userOff():
    """
    批量注销用户
    :param username: 用户名
    :return:
    """
    with ThreadPoolExecutor(10) as t:
        with open('account/user.txt', mode='r', encoding='utf-8')as f:
            for user in f:
                t.submit(baseScript.del_account, user)


def concurrent_register():
    with ThreadPoolExecutor(100) as t:
        for i in range(10000):
            t.submit(baseScript.register, i)
            if i % 200 == 0 and i > 0:
                time.sleep(5)
    print('over')


def add_memo(username):
    cookie = baseScript.login(username, 'cc1234')
    baseScript.add_memo_(cookie)




if __name__ == '__main__':
    # bind_devices('username31')
    # concurrent_login()
    # concurrent_register()
    username_list = []
    # print(len(data))
    # print(username_list)
    with open('account/protester.txt', mode='r', encoding='utf-8') as f:
        for username in f:
            username_list.append(username.strip())
    with ThreadPoolExecutor(100) as t:
        for username in username_list[2000:6000]:
            t.submit(add_memo, username.strip())
            # if username_list.index(username) == 1000:
            #     break






